<?php
/**
 * Created by PhpStorm.
 * User: Yieong
 * Date: 14/10/28
 * Time: 上午11:22
 */

class RealTimeService extends Service {


    public static function getKPIDict(){
        return array(
            'ALL'           => PubFunc::t('所有指标'),
            'PayMoney'      => PubFunc::t('充值金额'),
            'PayUser'       => PubFunc::t('充值人数'),
        	'PayCount'       => PubFunc::t('充值人次'),
        	'FirstPaymoney'      => PubFunc::t('首次充值金额'),
        	'FirstPayUser'       => PubFunc::t('首次充值人数'),
        	'FirstPayCount'       => PubFunc::t('首次充值人次'),
            'LoginUser'     => PubFunc::t('登录数'),
            'RoleUser'      => PubFunc::t('创建角色数'),
        	'RegUser'      => PubFunc::t('新注册账号数'),
            'AccountUser'   => PubFunc::t('去重创角用户数'),
            //'Online'        => PubFunc::t('在线')
        );
    }
    public static function fiveMinutesHeader($date){


        $end = strtotime($date);
        if($date == date('Y-m-d')){
            $begin = floor(time()/300) * 300;
            $begin = $begin - 20*60;
        }else{
            $begin = $end + 86400 - 300;
        }

        $minute = array();
        for(; $begin>=$end; $begin-=300){
            $min = date('H:i', $begin);
            $minute[$min] = array('text' => $min, 'rule' => 'numeric');
        }

        return array(
            'Kpi'       => array('text' => PubFunc::t('指标')),
            'Platform'  => array('text' => PubFunc::t('平台')),
            'SID'       => array('text' => PubFunc::t('服'), 'rule' => 'server'),
            //'Total'     => array('text' => PubFunc::t('累计')),
            'Minute'    => array('text' => PubFunc::t('分钟'), 'include' => $minute)
        );
    }

    public static function fiveMinutesTableData($data,$params){    	
        $tableData = array();
        $dict = self::getKPIDict();
        foreach($data as $kpi => $kpiData){
        	$keyFin = $params['os'] . "_" . $params['g'] . "_" . $params['server'] . "_" . $kpi;
        	if(!isset($tableFin[$keyFin])){
        		$tableFin[$keyFin] = array(
        				'Platform' => $params['os'],
        				'SID' => $params['server'],
        				'Kpi' => $dict[$kpi],
        		);
        	}
        	if(count($kpiData) == 0){       		
        		/**if($params['os'] != 'ALL' && $params['server'] != 'ALL'){
        			$key = $params['os'] . "_" . $params['g'] . "_" . $params['server'] . "_" . $kpi;
        			if(!isset($tableData[$key])){
        				$tableData[$key] = array(
        						'Platform' => $params['os'],
        						'SID' => $params['server'],
        						'Kpi' => $dict[$kpi],
        				);
        			}
        			
        			$tableData[$key]['Total'] = 0;
        			
        			$begin  = strtotime($params['date']);
        			$end    = strtotime($params['date']) + 86400;
        			for(;$begin<$end;$begin+=300){
        				if(!isset($tableData[$key][date('H:i', $begin)])){
        					$tableData[$key][date('H:i', $begin)] = 0;
        				}
        			}
        		}**/
        		

        	}else{
        		foreach($kpiData as $item){
        			if($params['os'] == 'ALL' && $params['server'] != 'ALL'){
        				$key = 'ALL' . "_" . $item['GameSrc'] . "_" . $item['SID'] . "_" . $item['KPI'];
        				$Platform = 'ALL';
        				$SID = $item['SID'];
        			}else if($params['os'] == 'ALL' && $params['server'] == 'ALL'){
        				$key = 'ALL' . "_" . $item['GameSrc'] . "_" . 'ALL' . "_" . $item['KPI'];
        				$Platform = 'ALL';
        				$SID = 'ALL';
        			}else{
        				$key = $item['Platform'] . "_" . $item['GameSrc'] . "_" . $item['SID'] . "_" . $item['KPI'];
        				$Platform = $item['Platform'];
        				$SID = $item['SID'];
        			}
        			if(!isset($tableData[$key])){
        				$tableData[$key] = array(
        						'Platform' => $Platform,
        						'SID' => $SID,
        						'Kpi' => $dict[$item['KPI']],
        				);
        			}
        			
        			$value = ($item['KPI'] == 'Online') ? $item['KPIValue'] : $item['CumKPIValue'];
        			$dayValue = $item['KPI'] == 'PayMoney' ? ($value ? $value : 0) : intval($value);        			
        			$tableData[$key][date('H:i', $item['RecDate'])] += $dayValue;
        			//$tableData[$key]['Total'] = PubStat::max($dayValue,$value);
        			
        			
//         			$key = $item['Platform'] . "_" . $item['GameSrc'] . "_" . $item['SID'] . "_" . $item['KPI'];
//         			if(!isset($tableData[$key])){
//         				$tableData[$key] = array(
//         						'Platform' => $item['Platform'],
//         						'SID' => $item['SID'],
//         						'Kpi' => $dict[$item['KPI']],
//         				);
//         			}
        		
//         			$value = ($item['KPI'] == 'Online') ? $item['KPIValue'] : $item['CumKPIValue'];
//         			$tableData[$key][date('H:i', $item['RecDate'])] = $item['KPI'] == 'PayMoney' ? ($value ? $value : 0) : intval($value);
//         			$tableData[$key]['Total'] = PubStat::max($tableData[$key]['Total'],$value);
        		}
        		
        		$begin  = strtotime($params['date']);
        		$end    = strtotime($params['date']) + 86400;
        		for(;$begin<$end;$begin+=300){
        			if(!isset($tableData[$key][date('H:i', $begin)])){
        				$tableData[$key][date('H:i', $begin)] = 0;
        			}
        		}
        	}   
        }
        
        foreach ($tableFin as $keyf=>$valf){
        	$key = $keyf;
        	if(!isset($tableData[$key])){
        		$tableData[$key] = array(
        				'Platform' => $valf['Platform'],
        				'SID' => $valf['SID'],
        				'Kpi' => $valf['Kpi'],
        		);
        	}
        	 
        	$tableData[$key]['Total'] = 0;

        	$begin  = strtotime($params['date']);
        	$end    = strtotime($params['date']) + 86400;
        	for(;$begin<$end;$begin+=300){
        		if(!isset($tableData[$key][date('H:i', $begin)])){
        			$tableData[$key][date('H:i', $begin)] = 0;
        		}
        	}
        }
        
        if($params['kpi'] == 'ALL'){
        	$tableData['APPPU']['Platform'] = $params['os'];
        	$tableData['APPPU']['SID'] = $params['server'];
        	$tableData['APPPU']['Kpi'] = 'APPPU';
        	
        	$tableData['login_APPPU']['Platform'] = $params['os'];
        	$tableData['login_APPPU']['SID'] = $params['server'];
        	$tableData['login_APPPU']['Kpi'] = '登录付费率';
        	
//         	$tableData['LTV']['Platform'] = $params['os'];
//         	$tableData['LTV']['SID'] = $params['server'];
//         	$tableData['LTV']['Kpi'] = 'LTV ';
        	
        	$key = $params['os'] . "_" . $params['g'] . "_" . $params['server'];
        	
        	$begin  = strtotime($params['date']);
        	$end    = strtotime($params['date']) + 86400;
        	for(;$begin<$end;$begin+=300){
        		if(!isset($tableData[$key][date('H:i', $begin)])){
        			$APPPU = $tableData[$key. "_PayCount"][date('H:i', $begin)] == 0? 0 : number_format($tableData[$key. "_PayMoney"][date('H:i', $begin)] / $tableData[$key. "_PayCount"][date('H:i', $begin)], 2, '.', '');
        			$login_APPPU = $tableData[$key. "_LoginUser"][date('H:i', $begin)] == 0? '0.00%' : number_format($tableData[$key. "_PayUser"][date('H:i', $begin)] / $tableData[$key. "_LoginUser"][date('H:i', $begin)] * 100, 2, '.', '')."%";
//         			$ltv = $tableData[$key. "_RoleUser"][date('H:i', $begin)] == 0? 0 : number_format($tableData[$key. "_PayMoney"][date('H:i', $begin)] / $tableData[$key. "_RoleUser"][date('H:i', $begin)], 2, '.', '');
        			$tableData['APPPU'][date('H:i', $begin)] = $APPPU;
        			$tableData['login_APPPU'][date('H:i', $begin)] = $login_APPPU;
//         			$tableData['LTV'][date('H:i', $begin)] = $ltv;
        		}
        	}
        }
//         echo '<pre/>';
//         var_dump($tableData);exit;
        return $tableData;
    }

    public static function fiveMinutesChartData($data, $flag){
    	
        $chartData = array();
        $dict = self::getKPIDict();
        foreach($data as $kpi => $kpiData) {
            foreach ($kpiData as $item) {
                if (!isset($chartData[$item['KPI']][$dict[$item['KPI']]])) {
                    $tableData[$item['KPI']][$dict[$item['KPI']]] = array();
                }
                if($flag == true){
	                $chartData[$item['SID']][date('H:i', $item['RecDate'])] = $item['KPI'] == "Online" ? intval($item['CumKPIValue']) : $item['CumKPIValue'];
                }else{
	                $chartData[$item['KPI']][$dict[$item['KPI']]][date('H:i', $item['RecDate'])] = $item['KPI'] == "Online" ? intval($item['CumKPIValue']) : $item['CumKPIValue'];
                }
            }
        }

        $retArr = array();
        
        $start = strtotime("2014-12-01");
        $end = $start + 86400 - 240;
        for(;$start < $end;$start+= 300){
            $key = date('H:i',$start);
            
            if($flag == true){
            	foreach($chartData as $key1 => $val1){
            		$tmpData = '';
            		
            		if($chartData[$key1][$key] === 0){
            			$tmpData = 0;
            		}else if(empty($chartData[$key1][$key])){
            			$tmpData = null;
            		}else{
            			$tmpData = $chartData[$key1][$key];
            		}
            		
            		$retArr['Online'][$key1][$key] = $tmpData; 
            		
            	}
            }else{
            	foreach($chartData as $key1 => $ii){
            		foreach($ii as $key2 => $i){
            			$tmpData = '';
            			if($chartData[$key1][$key2][$key] === 0){
            				$tmpData = 0 ;
            			}else if(empty($chartData[$key1][$key2][$key])){
            				$tmpData = null ;
            			}else{
            				$tmpData = $chartData[$key1][$key2][$key];
            			}
            			 
            			$retArr[$key1][$key2][$key] = $tmpData;
            		}
            	}
            }
        }
        
        return $retArr;
    }


    public static $defaultKPI = array(
    		//"Online","PayMoney","LoginUser","RoleUser","AccountUser"
        "PayMoney","PayUser","PayCount","FirstPaymoney","FirstPayUser","FirstPayCount","LoginUser","RoleUser","RegUser"
    );

    public static function fiveMinuteData($params){
    	//$params['os'] = '0';
    	//$params['server'] = 'd1_test_game1';
    	
        $data = array();
        
        if(!$params['g'])
            return $data;
        if($params['kpi'] == 'ALL'){
            $types = self::$defaultKPI;
            $flag  = false;
        }else{
            $types = array($params['kpi']);
            $flag  = true;
        }
        
        if($flag){
        	$separate = $params['separate'][0];
        }

        foreach($types as $type){
            $data[$type] = ModRealTime::getFiveMinuteData($params['os'],$params['g'],$params['server'],$type,$params['date'],$params['special_id'],$separate);             
        }
        
        return $data;
    }


    public static function visitHeader(){
        return array(
            'No'        => array('text' => PubFunc::t('序号')),
            'Time'      => array('text' => PubFunc::t('访问时间')),
            'Source'    => array('text' => PubFunc::t('入店来源')),
            'Page'      => array('text' => PubFunc::t('被访页面')),
            'Position'  => array('text' => PubFunc::t('访客位置')),
            'Trace'     => array('text' => PubFunc::t('访客跟踪')),
        );
    }

    public static function visitData(){
        $time = strtotime(date('Y-m-d'));
        $data = array();

        for($i=1; $i<30; $i++){
            $data[] = array(
                'No'        => $i,
                'Time'      => date('H:i:s', $time + rand(0,300)),
                'Source'    => PubFunc::t('直接访问'),
                'Page'      => PubFunc::t('首页'),
                'Position'  => PubFunc::t('中国'),
                'Trace'     => '<a href=\"javascript:;\">'.PubFunc::t("访客").$i.'</a>',
            );
        }

        return $data;
    }

    public static function perHourHeader($date){
        $end = strtotime($date);
        if($date == date('Y-m-d')){
            $begin = floor(time()/3600) * 3600;
        }else{
            $begin = $end + 86400 - 3600;
        }

        $arr = array();
        for(; $begin>=$end; $begin-=3600){
            $hour = date('H:i', $begin);
            $arr[$hour] = array('text' => $hour, 'rule' => 'numeric');
        }

        return array(
            'Kpi'       => array('text' => PubFunc::t('指标')),
            'Platform'  => array('text' => PubFunc::t('平台')),
            'SID'       => array('text' => PubFunc::t('服'), 'rule' => 'server'),
            'Total'     => array('text' => PubFunc::t('累计')),
            'Hour'      => array('text' => PubFunc::t('时'), 'include' => $arr)
        );
    }

    public static function perHourTableData($data){

        $tableData = array();
        $dict = self::getKPIDict();
        foreach($data as $kpi => $kpiData){
            foreach($kpiData as $item){
                $key = $item['Platform'] . "_" . $item['GameSrc'] . "_" . $item['SID'] . "_" . $item['KPI'];
                if(!isset($tableData[$key])){
                    $tableData[$key] = array(
                        'Platform' => $item['Platform'],
                        'SID' => $item['SID'],
                        'Kpi' => $dict[$item['KPI']],
                    );
                }

                $hr = sprintf("%02d:00", $item['HR']);
                $value = ($item['KPI'] == 'Online') ? $item['KPIValue'] : $item['CumKPIValue'];
                $tableData[$key][$hr] = $item['KPI'] == 'PayMoney' ? ($value ? $value : 0) : intval($value);
                $tableData[$key]['Total'] = PubStat::max($tableData[$key]['Total'],$value);
            }
        }

        return $tableData;
    }

    public static function perHourChartData($data, $today=false){

        $chartData = array();
        $dict = self::getKPIDict();

        foreach($data as $kpi => $kpiData){
            // 初始化
            for($i=1; $i<25; $i++){
                $hr = sprintf('%02d:00', $i);
                $chartData[$kpi][$dict[$kpi]][$hr] = 0;
            }

            foreach($kpiData as $v){
                $hr = sprintf('%02d:00', $v['HR']);

                if($v['KPI'] == 'Online'){
                    $chartData[$kpi][$dict[$kpi]][$hr] = $v['KPIValue'];
                }else{
                    $chartData[$kpi][$dict[$kpi]][$hr] = $v['CumKPIValue'];
                }
            }

            if($today){
                $currentHr = date('G');
                // 初始化
                for($j=$currentHr; $j<25; $j++){
                    $hr = sprintf('%02d:00', $j);
                    if(empty($chartData[$kpi][$dict[$kpi]][$hr])) {
                        $chartData[$kpi][$dict[$kpi]][$hr] = null;
                    }
                }
            }
        }

        return $chartData;
    }

    public static function perHourData($params){
        $data = array();

        if(!$params['g'])
            return $data;
        if($params['kpi'] == 'ALL'){
            $types = self::$defaultKPI;
            $flag  = false;
        }else{
            $types = array($params['kpi']);
            $flag  = true;
        }

        if($flag){
            $separate = $params['separate'][0];
        }

        foreach($types as $type){
            $data[$type] = ModRealTime::getHourData($params['p'],$params['g'],$params['server'],$type,$params['date'], $separate);
        }

        return $data;
    }
} 